//
//  VideoWorksViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/8/19.
//

import UIKit
import Photos
import JXSegmentedView

class VideoWorksViewController: BaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, JXSegmentedListContainerViewListDelegate {
    let viewModel = VideoHistoryViewModel()
    let disposeBag = DisposeBag()
    let releaseViewModel = WorksViewModel()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        self.editNav(isCurrent: true)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let height = (SCREEN_WIDTH - 47) / 2
        layout.itemSize = CGSize(width: Int(height), height: Int(height + 80))
        layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 64 + bottomSafeAreaHeight, right: 16)
        // 设置每行的项目数量
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(cellWithClass: VideoWorksHistoryItemCell.self)
        collectionView.backgroundColor = UIColor.clear // 设置背景颜色
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.emptyDataSetSource = self
        collectionView.emptyDataSetDelegate = self
        return collectionView
    }()
    
    private lazy var descGenerateBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "发布"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.titleColorForNormal = .white
        button.allRound(27)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.isHidden = true
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        self.view.addSubview(self.collectionView)
        self.view.addSubview(descGenerateBtn)
        self.navigationItem.title = "我的视频"
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.bottom.equalToSuperview()
        } 
        
        descGenerateBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-10)
            make.leading.trailing.equalToSuperview().inset(32)
            make.height.equalTo(54)
        }
        
        self.viewModel.reloadDataSubject.subscribe(onNext: { [weak self] in
            self?.collectionView.reloadData()
        }).disposed(by: disposeBag)
        
        self.viewModel.getVideoList()

        descGenerateBtn.setClosureTouchUpInside_k { [weak self] in
            self?.generate()
        }
        
        releaseViewModel.reloadListSubject.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            self.reload()
            let vc = ReleaseViewController()
            vc.type = 1
            self.navigationController?.pushViewController(vc)
        }).disposed(by: disposeBag)
        
        
        releaseViewModel.errorSubject.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            self.reload()
            let vc = ReleaseViewController()
            vc.type = 2
            self.navigationController?.pushViewController(vc)
        }).disposed(by: disposeBag)

    }
    
    func reload(){
        self.descGenerateBtn.isHidden = true
        for (index, value) in self.viewModel.videoArr.enumerated() {
            self.viewModel.videoArr[index].isSelect = false
        }
        self.collectionView.reloadData()
    }
    func generate(){
        if let model = self.viewModel.videoArr.first(where: { $0.isSelect == true } ) {
            self.releaseViewModel.releaseWorks(id: "\(model.id ?? 0)", type: 2)
        }else {
            NDProgressHUD.show(message: "请选择作品，在尝试发布。")
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.viewModel.videoArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = self.viewModel.videoArr[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withClass: VideoWorksHistoryItemCell.self, for: indexPath)
        cell.setup(model: model)
        if model.sts == 1 {
            cell.activityIndicator.isHidden = false
            cell.generatingLb.isHidden = false
            cell.activityIndicator.startAnimating()
            cell.saveBtn.isHidden = true
        }else {
            cell.activityIndicator.isHidden = true
            cell.generatingLb.isHidden = true
            cell.activityIndicator.stopAnimating()
            if model.sts == 2 {
                cell.saveBtn.isHidden = false
            }
        }
        cell.selectBtn.isSelected = model.isSelect
        if model.isSelect {
            cell.iconIV.layer.borderWidth = 2
            cell.iconIV.layer.borderColor = UIColor(hexString: "#45DFFF").cgColor
        }else {
            cell.iconIV.layer.borderWidth = 2
            cell.iconIV.layer.borderColor = UIColor.clear.cgColor
        }
        cell.saveBtn.setClosureTouchUpInside_k { [weak self] in
//            if let url = URL(string: model.video_url) {
//                self?.saveVideoToAlbum(from: url)
//            }
            let vc = VideoGeneratingVC()
            vc.ids = model.order_no ?? ""
            self?.navigationController?.pushViewController(vc)
        }
        
        cell.selectBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            for (index, value) in self.viewModel.videoArr.enumerated() {
                self.viewModel.videoArr[index].isSelect = false
            }
            if model.isSelect {
                self.viewModel.videoArr[indexPath.item].isSelect = false
            }else {
                self.viewModel.videoArr[indexPath.item].isSelect = true
            }
            self.collectionView.reloadData()
            checkState()
        }
        return cell
    }
    
    func checkState(){
        if let model = self.viewModel.videoArr.first(where: { $0.isSelect == true } ) {
            descGenerateBtn.isHidden = false
        }else {
            descGenerateBtn.isHidden = true
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        let model = self.viewModel.videoArr[indexPath.item]
//        let vc = VideoGeneratingVC()
//        vc.ids = model.order_no ?? ""
//        self.navigationController?.pushViewController(vc)
    }
    
    
    func saveVideoToAlbum(from url: URL) {
        // 显示加载进度
        NDProgressHUD.showLoading()
        // 使用 URLSession 下载视频
        let session = URLSession(configuration: .default)
        let downloadTask = session.downloadTask(with: url) { location, response, error in
            guard let location = location, error == nil else {
                // 下载失败
                NDProgressHUD.showError(title: "", subtitle: "Download failed: \(error?.localizedDescription ?? "Unknown error")")
                return
            }
            do {
                // 获取临时文件路径
                let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
                let tempFileURL = tempDirectoryURL.appendingPathComponent(url.lastPathComponent)
                // 移动文件到临时路径
                try FileManager.default.moveItem(at: location, to: tempFileURL)
                // 请求相册权限
                PHPhotoLibrary.requestAuthorization { status in
                    if status == .authorized {
                        NDProgressHUD.showLoading()
                        // 保存视频到相册
                        PHPhotoLibrary.shared().performChanges({
                            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: tempFileURL)
                        }) { success, error in
                            DispatchQueue.main.async {
                                if success {
                                    NDProgressHUD.showSuccess(title: "", subtitle: "视频保存成功!")
                                } else {
                                    NDProgressHUD.showError(title: "", subtitle: "Save failed: \(error?.localizedDescription ?? "Unknown error")")
                                }
                                // 删除临时文件
                                try? FileManager.default.removeItem(at: tempFileURL)
                            }
                        }
                    } else {
                        NDProgressHUD.showError(title: "", subtitle: "没有相册权限")
                    }
                }
            } catch {
                NDProgressHUD.showError(title: "", subtitle: "File handling failed: \(error.localizedDescription)")
            }
        }
        downloadTask.resume()
    }
    
    func listView() -> UIView {
        return self.view
    }
}

extension VideoWorksViewController: DZNEmptyDataSetDelegate, DZNEmptyDataSetSource {
    open func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        UIImage(named: "icon_nodata")
    }
    
    open func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let text = "暂无数据，点击刷新～"
        let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.pingFangSCRegular(ofSize: 15), .foregroundColor: Theme.color.text_d3]
        return NSAttributedString(string: text, attributes: attributes)
    }
    
    func emptyDataSet(_ scrollView: UIScrollView!, didTap view: UIView!) {
        self.viewModel.getVideoList()
    }
}

class VideoWorksHistoryItemCell: UICollectionViewCell {
     lazy var iconIV: UIImageView = {
        let imageView = UIImageView()
        imageView.allRound(4)
        imageView.contentMode = .scaleAspectFill
        imageView.layer.masksToBounds = true
        imageView.clipsToBounds = true
        imageView.backgroundColor = UIColor(hexString: "#25262B")
        return imageView
    }()
    
    lazy var activityIndicator: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(style: .white)
        indicator.hidesWhenStopped = true
        indicator.isHidden = true
        return indicator
    }()
    
    
    lazy var generatingLb: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#FFFFFF", transparency: 0.7)
        label.font = UIFont.pingFangSCRegular(ofSize: 10)
        label.text = "正在生成中..."
        label.isHidden = true
        return label
    }()
    
//    lazy var stateLb: UILabel = {
//        let label = UILabel()
//        label.textColor = UIColor(hexString: "#49FF5B")
//        label.font = UIFont.pingFangSCRegular(ofSize: 9)
//        label.backgroundColor = UIColor(hexString: "#000000", transparency: 0.7)
//        label.allRound(7.5)
//        // 创建 NSTextAttachment 并设置图标
//        let attachment = NSTextAttachment()
//        attachment.image = UIImage(named: "icon_video_ysave") // 替换 "icon_name" 为您的图标文件名
//        attachment.bounds = CGRect(x: 0, y: 0, width: 9, height: 9) // 根据需要调整图标大小和位置
//        // 创建带有图标的 NSAttributedString
//        let attachmentString = NSAttributedString(attachment: attachment)
//        // 创建文本的 NSAttributedString
//        let space = NSAttributedString(string: " ")
//        let textString = NSAttributedString(string: "已保存")
//        // 将图标和文本组合在一起
//        let combinedString = NSMutableAttributedString()
//        combinedString.append(space)
//        combinedString.append(attachmentString)
//        combinedString.append(space)
//        combinedString.append(textString)
//        combinedString.append(space)
//        // 将组合后的字符串设置为标签的 attributedText
//        label.attributedText = combinedString
//        return label
//    }()
//    
    lazy var saveBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_com_player")
        return button
    }()
    
    lazy var selectBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_works_nor")
        button.imageForSelected = UIImage(named: "icon_works_sel")
        return button
    }()
    
    private lazy var timeLb: UILabel = {
        let label = UILabel()
        label.textColor = Theme.color.text_d3
        label.font = UIFont.pingFangSCRegular(ofSize: 14)
        label.text = "2024-04-24 23:23"
        label.textAlignment = .center
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        let height = (SCREEN_WIDTH - 47) / 2
        contentView.addSubviews([iconIV, activityIndicator, generatingLb, saveBtn, timeLb, selectBtn])
        
        activityIndicator.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(iconIV)
            make.width.height.equalTo(36)
        }
        
        generatingLb.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(activityIndicator.snp.bottom).offset(10)
        }
        
        iconIV.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(Int(height + 56))
        }
        
        saveBtn.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(iconIV)
            make.height.width.equalTo(30)
        }
        
        selectBtn.snp.makeConstraints { make in
            make.bottom.equalTo(iconIV.snp.bottom).offset(-10)
            make.leading.equalTo(iconIV.snp.leading).offset(10)
        }
        
        timeLb.snp.makeConstraints { make in
            make.top.equalTo(iconIV.snp.bottom).offset(6)
            make.leading.trailing.equalToSuperview()
        }
    }
    
    func setup(model:VideoHistoryModel) {
        iconIV.sd_setImage(with: URL(string: model.cover_url ?? ""))
        
        // 定义日期字符串
        let isoDateString = model.create_time ?? ""
        // 处理时间字符串
        let displayDateString = convertISODateStringToChineseLocalString(isoDateString)
        self.timeLb.text = displayDateString
    }
    
    func convertISODateStringToChineseLocalString(_ isoDateString: String) -> String? {
        // 创建 DateFormatter 对象来解析时间字符串
        let isoDateFormatter = DateFormatter()
        isoDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" // 修改这里
        isoDateFormatter.locale = Locale(identifier: "en_US_POSIX")

        // 将时间字符串转换为 Date 对象
        if let date = isoDateFormatter.date(from: isoDateString) {
            // 创建用于显示的 DateFormatter 对象
            let displayDateFormatter = DateFormatter()
            displayDateFormatter.dateFormat = "yyyy年MM月dd日 HH:mm"
            displayDateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // 设置为 UTC 时间

            // 将 Date 对象转换为指定格式的字符串
            let displayDateString = displayDateFormatter.string(from: date)
            return displayDateString
        } else {
            print("日期格式无效")
            return nil
        }
    }


    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
